package com.doujiang.service;

import com.doujiang.domain.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 验证码服务类
 */
@Service
public class VerificationCodeService {
    
    @Autowired
    private EmailService emailService;
    
    // 存储验证码的Map，key为邮箱，value为验证码对象
    private final Map<String, VerificationCode> codeMap = new ConcurrentHashMap<>();
    
    // 存储发送次数的Map，用于限制发送频率
    private final Map<String, Integer> sendCountMap = new ConcurrentHashMap<>();
    
    /**
     * 生成并发送验证码
     */
    public boolean generateAndSendCode(String email) {
        return generateAndSendCode(email, false);
    }
    
    /**
     * 生成并发送验证码（支持重置密码）
     */
    public boolean generateAndSendCode(String email, boolean isResetPassword) {
        // 检查发送频率限制
        if (!checkSendLimit(email)) {
            return false;
        }
        
        // 生成6位数字验证码
        String code = String.format("%06d", new Random().nextInt(1000000));
        
        // 存储验证码
        codeMap.put(email, new VerificationCode(code, System.currentTimeMillis()));
        
        // 更新发送次数
        updateSendCount(email);
        
        try {
            // 发送验证码邮件
            if (isResetPassword) {
                emailService.sendResetPasswordCode(email, code);
            } else {
                emailService.sendVerificationCode(email, code);
            }
            return true;
        } catch (Exception e) {
            // 发送失败，移除验证码
            codeMap.remove(email);
            return false;
        }
    }
    
    /**
     * 验证验证码
     */
    public boolean verifyCode(String email, String code) {
        VerificationCode stored = codeMap.get(email);
        if (stored != null && stored.isValid(code)) {
            // 验证成功后移除验证码
            codeMap.remove(email);
            return true;
        }
        return false;
    }
    
    /**
     * 检查发送频率限制
     */
    private boolean checkSendLimit(String email) {
        Integer count = sendCountMap.get(email);
        if (count == null) {
            return true;
        }
        
        // 如果5分钟内发送超过3次，则限制
        return count < 3;
    }
    
    /**
     * 更新发送次数
     */
    private void updateSendCount(String email) {
        Integer count = sendCountMap.get(email);
        if (count == null) {
            count = 0;
        }
        sendCountMap.put(email, count + 1);
        
        // 5分钟后重置发送次数
        new Thread(() -> {
            try {
                Thread.sleep(5 * 60 * 1000); // 5分钟
                sendCountMap.remove(email);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
} 